<?php

namespace app\common\service;

use app\common\model\Area;
use ip138\Ip138;
use ShidianUtil\Utils\ArrayUtil;
use ShidianUtil\Utils\ConvertUtil;

/**
 *
 * Class AreaService
 * @package app\common\service
 */
class AreaService
{
    private Ip138 $ip138;

    public function __construct(Ip138 $ip138)
    {
        $this->ip138 = $ip138;
    }

    public function getProvinceCityByPhone($phone): array
    {
        ['provinceName' => $provinceName, 'cityName' => $cityName] = $this->getPCName($phone);
        return $this->getAreas($provinceName, $cityName);
    }

    private function getPCName($phone)
    {
        $response = $this->ip138->getCityByPhone($phone);

        $result = (string)$response->getBody();

        if (is_blank($result)) {
            return [
                'provinceName' => null,
                'cityName' => null,
            ];
        }
        $result = ConvertUtil::jsonDecode($result);

        $provinceName = $result['data'][0] ?? '';
        $cityName = $result['data'][1] ?? '';
        if (is_blank($cityName) && not_blank($provinceName)) {
            $cityName = $provinceName;
        }

        return [
            'provinceName' => $provinceName,
            'cityName' => $cityName,
        ];

    }

    private function getAreas($provinceName, $cityName)
    {
        $province = null;
        $city = null;

        // 查询
        $limit = 0;
        $query = Area::field(true);
        if (not_blank($provinceName)) {
            $query->whereOr(function ($query) use ($provinceName) {
                $query->whereLike('name', $provinceName . '%')
                      ->where('province', 0)
                      ->where('city', 0)
                      ->where('status', 0);
            });
            $limit++;
        }
        if (not_blank($cityName)) {
            $query->whereOr(function ($query) use ($cityName) {
                $query->whereLike('name', $cityName . '%')
                      ->where('province', '<>', 0)
                      ->where('city', 0)
                      ->where('status', 0);
            });
            $limit++;
        }

        if ($limit != 0) {
            $areas = $query->limit($limit)->select();

            $province = ArrayUtil::find($areas->all(), function ($area) {
                return $area->province == 0 && $area->city == 0;
            });

            $city = ArrayUtil::find($areas->all(), function ($area) {
                return $area->province != 0 && $area->city == 0;
            });
        }

        return [
            'province' => $province,
            'city' => $city,
        ];
    }

}
